package com.zee.home.controller;

import com.zee.common.model.response.Result;
import com.zee.home.annotation.Login;
import com.zee.home.entity.User;
import com.zee.home.model.dto.LoginDTO;
import com.zee.home.model.dto.RegisterDTO;
import com.zee.home.service.IUserService;
import com.zee.home.service.IUserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 登录接口
 *
 * @author Mark LinZee
 * @email LinZee666@163.com
 */
@RestController
@RequestMapping("/api/index")
@Api(tags = "注册登录接口")
public class IndexController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserTokenService tokenService;


    @PostMapping("login")
    @ApiOperation("登录")
    public Result login(@RequestBody LoginDTO dto) {
        //用户登录
        Map<String, Object> map = userService.login(dto);

        return Result.ok(map);
    }

    @PostMapping("register")
    @ApiOperation("注册")
    public Result register(@RequestBody RegisterDTO dto) {

        User user = new User();
        user.setMobile(dto.getMobile());
        user.setUsername(dto.getMobile());
        user.setPassword(DigestUtils.sha256Hex(dto.getPassword()));
        user.setCreateTime(LocalDateTime.now());
        userService.save(user);

        return Result.ok();
    }

    @Login
    @PostMapping("logout")
    @ApiOperation("退出")
    public Result logout(@ApiIgnore @RequestAttribute("userId") Integer userId) {
        tokenService.expireToken(userId);
        return Result.ok();
    }

}